// Fill out your copyright notice in the Description page of Project Settings.


#include "Test/Test.h"

FCountRunnable::FCountRunnable(AAnsyActor* InOwner) : Owner(InOwner),bStop(false)
{
	
}

FCountRunnable::~FCountRunnable()
{
}

bool FCountRunnable::Init()
{
	UE_LOG(LogTemp, Warning, TEXT("Count"));
	return true;
}

uint32 FCountRunnable::Run()
{
	while (!bStop)
	{
		if (!Owner) break;
		int32 CurrentCount = Owner->GetCurrentCount();
		CurrentCount++;
		//更新计数
		Owner->SetCurrentCount(CurrentCount);
		if (CurrentCount % 100 == 0)
		{
			//UE_LOG(LogTemp, Warning, TEXT("Current Count: %d"), CurrentCount);
			CurrentCountQue.Enqueue(CurrentCount);
			int32 DequeueCount;
			if (CurrentCountQue.Dequeue(DequeueCount))
			{
				UE_LOG(LogTemp, Warning, TEXT("DequeueCount: %d"), DequeueCount);
			}
		}
		FPlatformProcess::Sleep(0.001f);

		if (CurrentCount >= 10000)
		{
			break;
		}
	}
	return 0;
}

void FCountRunnable::Stop()
{
	//FRunnable::Stop();
	bStop = true;
}

void FCountRunnable::Exit()
{
	FRunnable::Exit();
	UE_LOG(LogTemp, Log, TEXT("退出"));
}

AAnsyActor::AAnsyActor()
{
	CurrentCount = 0;
	CountRunnable = nullptr;
	CountThread = nullptr;
}

AAnsyActor::~AAnsyActor()
{
	StopFRunnableCount();
}

void AAnsyActor::StartFRunnableCount()
{
	CurrentCount = 0;
	// 创建Runnable实例（传入this指针）
	CountRunnable = new FCountRunnable(this);
	// 创建并启动线程
	CountThread  = FRunnableThread::Create(CountRunnable,TEXT("CountThread"));
	if (!CountThread)
	{
		delete CountRunnable;
		CountRunnable = nullptr;
	}
}

void AAnsyActor::StopFRunnableCount()
{
	if (CountRunnable)
	{
		CountRunnable->Stop();
	}

	if (CountThread)
	{
		// 等待线程真正退出（超时时间：1秒）
		CountThread->WaitForCompletion();
		delete CountThread;
		CountThread = nullptr;
	}

	if (CountRunnable)
	{
		delete CountRunnable;
		CountRunnable = nullptr;
	}
}

int32 AAnsyActor::GetCurrentCount() const
{
	return CurrentCount.load();
}

void AAnsyActor::SetCurrentCount(int32 NewCount)
{
	CurrentCount = NewCount;
}

void AAnsyActor::BeginPlay()
{
	StartFRunnableCount();
	Super::BeginPlay();
}

void AAnsyActor::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
	StopFRunnableCount();
	Super::EndPlay(EndPlayReason);
}

